import { _login } from '../../api/user'
const tokenKey = 'token'
const userInfoKey = 'userInfo'
const state = {
  token: uni.getStorageSync('token') || '',
  userInfo: uni.getStorageSync('userInfo') || {}
}

const mutations = {
  /**
   *  保存用户token和用户信息到Vuex
   */
  setUserInfo(state, { token, userInfo }) {
    state.token = token
    state.userInfo = userInfo
    this.commit('user/setUserInfoStorage')
    this.commit('user/setTokenStorage')
  },
  /**
   * 保存用户用户信息到本地存储
   */
  setUserInfoStorage(state) {
    uni.setStorage({
      key: userInfoKey,
      data: state.userInfo
    })
  },
  /**
   * 保存用户token到本地存储
   */
  setTokenStorage(state) {
    uni.setStorage({
      key: tokenKey,
      data: state.token
    })
  },
  /**
   * 删除 token
   */
  removeToken(state) {
    state.token = ''
    uni.removeStorageSync('token')
  },
  /**
   * 删除 用户信息
   */
  removeUserInfo(state) {
    state.userInfo = {}
    uni.removeStorageSync('userInfo')
  }
}

const actions = {
  /**
   * 登录
   */
  async login(context, userData) {
    const { nickName, gender, city, province, avatarUrl } = userData.userInfo
    console.log(nickName, gender, city, province, avatarUrl)
    const obj = {
      signature: userData.signature,
      iv: userData.iv,
      nickName: nickName,
      gender: gender,
      city: city,
      province: province,
      avatarUrl: avatarUrl
    }
    const { token } = await _login(obj)
    context.commit('setUserInfo', { token: token, userInfo: userData.userInfo })
  },
  /**
   * 退出登录
   */
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
